from QQLoginTool.QQtool import OAuthQQ
from rest_framework.response import Response
from rest_framework.views import APIView
from mall import settings
from oauth.models import OAuthQQUser
from oauth.serializers import CodeQQAPIViewSerializer
from oauth.utils import make_openid
from utils.setjwt import set_jwt

'''
get
进行返回
拼接url
从qq返回code
'''


class QQAuthURLView(APIView):

    def get(self,request):

        # 初始化
        state = 'text'
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        # 拼接url
        auth_url = qq.get_qq_url()
        # 返回响应
        return Response({'auth_url':auth_url})


'''
1 由前端传来的code
2 后端接收　并且向qq发送换取token

'''
'''
逻辑　请求方式　post
参数　　手机号　密码　短信验证码　openid
进行校验　　序列化器的选择　　
进行保存

'''


class CodeQQAPIView(APIView):

    # GET /oauth/qq/users/?code=xxx
    def get(self,request):
        # 获得code
        code = request.query_params.get('code')
        # 验证code 是否有值
        if code is None:
            from rest_framework import status

            return Response(status= status.HTTP_404_NOT_FOUND)

        # 进行初始化
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI)
        # 取到token的值
        token = qq.get_access_token(code)
        # 取到openid 的值
        openid = qq.get_open_id(token)

        try:
            qquser = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            # 调用函数进行功能的实现　进行加密
            open_token_id = make_openid(openid)
            return Response({'access_token':open_token_id})

        else:
            # 说明存在， 存在应该登陆
            # 返回 token，username,userid
            token = set_jwt(qquser.user)

            return  Response({
                'user_id':qquser.user.id,
                'username':qquser.user.username,
                'token':token
            })

    def post(self,request):

        data = request.data

        serializer = CodeQQAPIViewSerializer(data=data)
        serializer.is_valid(raise_exception=True)

        user = serializer.save()
        token = set_jwt(user)
        data ={
            'token':token,
            'username':user.username,
            'user_id':user.id
        }
        return Response(data)











